<?php
	// Check crossing acess
	if (!defined('RIGHT_ACCESS') || !defined('ROOT_FOLDER'))
	{
		header('Content-Type: text/xml; charset=utf-8');
		echo '<?xml version="1.0"?>';
		echo '<atomtask>';
		echo '<request>error.request.invalid</request>';
		echo '</atomtask>';
		return;
	}	

	// Include functions
	include_once(ROOT_FOLDER.'includes/user_func.php');
	include_once(ROOT_FOLDER.'db/connect_db.php');

	// Not enough information
	if (!isset($_POST['username']) || !isset($_POST['password']) || !isset($_POST['email']))
	{
		XML::write_element('result', 'error.user.register.invalid_input');
		return;
	}
	if (!User::is_valid_username($_POST['username']) || !User::is_valid_password($_POST['password']) || !User::is_valid_email($_POST['email']))
	{
		XML::write_element('result', 'error.user.register.invalid_input');
		return;
	}
	// Binding data
	$user = new User();
	$user->username = Text::standardize($_POST['username']);
	$user->password = Text::standardize($_POST['password']);
	$user->email = Text::standardize($_POST['email']);
	// Check exist
	$exist_count = $user->check_exist();
	if ($exist_count != 0)
	{
		if ($exist_count == 1 || $exist_count == 3)
			XML::write_element('result', 'error.user.register.username_existing');
		if ($exist_count == 2 || $exist_count == 3)
			XML::write_element('result', 'error.user.register.email_existing');
		return;
	}

	// Add new user
	if (!$user->create())
	{
		XML::write_element('result', 'error.request.unknown');
		return;
	}
	XML::write_element('result', 'success.user.register');
?>